package com.intlke.example.app;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.ProgressCallback;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<>();
        boolean overwrite = true;
        // 修改后（正确方式）
        URL resource = App.class.getClassLoader().getResource("generatorConfig.xml");
        if (resource == null) {
            throw new FileNotFoundException("无法在classpath中找到generatorConfig.xml");
        }
        File configFile = new File(resource.toURI());
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);

        ProgressCallback progressCallback = new ProgressCallback() {
            @Override
            public void introspectionStarted(int totalTasks) {
                System.out.println("开始进行数据库表结构内省，总任务数: " + totalTasks);
            }

            @Override
            public void generationStarted(int totalTasks) {
                System.out.println("开始代码生成，总任务数: " + totalTasks);
            }

            @Override
            public void saveStarted(int totalTasks) {
                System.out.println("开始保存生成的代码，总任务数: " + totalTasks);
            }

            @Override
            public void startTask(String taskName) {
                System.out.println("开始任务: " + taskName);
            }

            @Override
            public void done() {
                System.out.println("代码生成完成");
            }

            @Override
            public void checkCancel() throws InterruptedException {
                // 可在此处检查是否取消操作
            }
        };

        Set<String> contextIds = Collections.singleton("simple");
        boolean writeFiles = true;
        Set<String> tablesToGenerate = Collections.singleton("sys_config"); // 需要生成的表集合
        myBatisGenerator.generate(progressCallback, contextIds, tablesToGenerate, writeFiles);
        // 检查生成日志
        warnings.forEach(System.out::println);
    }
}
